<?php

class AuthorManager extends Manager
{
	const TABLE_NAME = 'autorzy';
	const RELATIONTABLE_BOOKS_NAME = 'wydanieautor';
	const OBJECT_NAME = 'Author';

	public function getById($id)
	{
		$select = $this->_db->select()->from(self::TABLE_NAME)
					->where('id = ?', $id);
		$result = $this->_db->fetchRow($select);
		return $this->_createObject(self::OBJECT_NAME, $result);
	}

	public function getAll()
	{
		$select = $this->_db->select()->from(self::TABLE_NAME)->order(array('nazwisko ASC', 'imie ASC'));
		return $this->_fetchCollection(self::OBJECT_NAME, $select);
	}
	
	public function getMainByEditionIsbn($isbn)
	{
		$select = $this->_db->select()->from(self::TABLE_NAME, self::TABLE_NAME . '.*')
					->join(EditionManager::TABLE_NAME, 
						EditionManager::TABLE_NAME . '.glownyAutor = ' . self::TABLE_NAME . '.id', '')
					->where(EditionManager::TABLE_NAME . '.isbn = ?', $isbn);
					
		return $this->_fetchObject(self::OBJECT_NAME, $select);
	}

	public function getByEditionIsbn($isbn)
	{
		$select = $this->_db->select()->from(self::TABLE_NAME, self::TABLE_NAME . '.*')
					->join(self::RELATIONTABLE_BOOKS_NAME, 
						self::RELATIONTABLE_BOOKS_NAME . '.idAutora = ' . self::TABLE_NAME . '.id', '')
					->where(self::RELATIONTABLE_BOOKS_NAME . '.idWydania = ?', $isbn);
					
		$result = $this->_db->fetchAll($select);
		return $this->_createCollection(self::OBJECT_NAME, $result);
	}
	
	public function getAllByEditionIsbn($isbn)
	{
		$main = $this->getMainByEditionIsbn($isbn);
		$others = $this->getByEditionIsbn($isbn);

		if ($main) {
			return array_merge(array($main), $others);
		} else {
			return $others;
		}
		
	}
	
}